#include "primitiveploy.h"

int PrimitivePloy::findfirst1() {
  int fsize = 63;
  while (fsize > 0) {
    if (poly[fsize]) {
      break;
    }
    fsize--;
  }
  return fsize;
}

PrimitivePloy::PrimitivePloy() : poly(0) {}

int PrimitivePloy::size() const { return _size; }

void PrimitivePloy::set(unsigned long long num) {
  poly = num;
  _size = findfirst1();
  initPolyLinkList();
}

void PrimitivePloy::initPolyLinkList() {
  polyLinkList.clear();
  poly1pos.clear();
  polyLinkList.reserve(_size);
  for (int i = 0; i < _size; i++) {
    polyLinkList.push_back(QVector<int>{i});
    if (poly[i] == 1 && i > 0) {
      poly1pos.push_back(i);
    }
  }

  // LFSR

  for (int i = 0; i < 8; i++) {
    auto front = polyLinkList.back();
    polyLinkList.pop_back();
    polyLinkList.push_front(front);
    for (auto i : poly1pos) {
      polyLinkList[i].append(front);
    }
  }

  //化简
  std::bitset<64> pattern;
  for (auto &_poly : polyLinkList) {
    pattern = 0;
    while (!_poly.empty()) {
      auto id = _poly.back();
      _poly.pop_back();
      pattern[id] = pattern[id] ^ 1;
    }
    for (int i = 0; i < _size; i++) {
      if (pattern[i]) {
        _poly.push_back(i);
      }
    }
  }
}
